package com.arm.controller;

import com.arm.def.Constant;
import com.arm.def.FixedData;
import com.arm.module.User;
import com.arm.module.weChat.UserWechatInfo;
import com.arm.service.UserService;
import com.arm.tools.WeiXinUtils;
import com.arm.tools.myRunTime.MyRunTimeExcption;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Baggio on 2019-1-8.
 */
public class WechatBaseController extends BaseController {


    @Autowired
    protected UserService userService;

    /**
     * 获取客户端浏览器来源是否是微信浏览器
     * (此功能暂时未完善)
     *
     * @param request
     * @return
     */
    protected boolean getBrowserSource(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.indexOf("micromessenger") > -1) {
            logger.info("微信浏览器======》》》");
            return true;
        }
        logger.info("不是微信浏览器======》》》");

        return false;

    }


    /**
     * 判断客户端是否是移动端
     *
     * @param request
     * @return
     */
    protected boolean getIsMobile(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");
        String[] agent = {
                "Android"
                , "iPhone"
                , "iPod"
                , "iPad"
                , "Windows Phone"
                , "micromessenger"
                , "MQQBrowser"};

        boolean flag = false;
        if (
                !userAgent.contains("Windows NT")
                        || (userAgent.contains("Windows NT") && userAgent.contains("compatible; MSIE 9.0;"))) {

            // 排除 苹果桌面系统
            if (!userAgent.contains("Windows NT") && !userAgent.contains("Macintosh")) {
                for (String item : agent) {
                    if (userAgent.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 微信授权
     *
     * @param request
     * @param response
     */

    protected void oauth2(HttpServletRequest request, HttpServletResponse response) {

        if (!getBrowserSource(request)) {
            logger.info("不是微信浏览器，不能鉴权");
         /*   User user = userService.bindUser("testOpenId");
            request.getSession().setAttribute(Constant.SESSION_KEY_USER_LOGIN, user);
            logger.info("为了测试乱写一个openID");*/
            return;
        }
        User user = (User) request.getSession().getAttribute(Constant.SESSION_KEY_USER_LOGIN);
        if (user != null) {
            logger.info("已经鉴权，不用再次鉴权=====》》》》》》" + user.getOpenId());
            return;
        }
        String code = request.getParameter("code");
        if (StringUtils.isNotBlank(code)) {
            //获取openId
            getOpenId(request, code);
            return;
        }


        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String toUrl = "http://" + request.getServerName() //服务器地址
               /* + ":"
                + request.getServerPort()           //端口号
                */
                + httpRequest.getContextPath()      //项目名称
                + httpRequest.getServletPath();      //请求页面或其他地址

        String queryStr = httpRequest.getQueryString();
        if (StringUtils.isNotBlank(queryStr)) {
            toUrl += "?" + queryStr; //参数
        }


        logger.info(" ===========================u==============================================>/n" + toUrl);
        String u = WeiXinUtils.oauth2(toUrl, WeiXinUtils.SNSAPI_BASE);
        logger.info(" ===========================u==============================================>/n" + u);
        try {
            response.sendRedirect(u);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    protected void getOpenId(HttpServletRequest request, String code) throws MyRunTimeExcption {

        UserWechatInfo userWechatInfo = WeiXinUtils.getUserInfoInWechat(FixedData.ENTERPRISE_APP_ID, code);
        if (userWechatInfo == null) {
            throw new MyRunTimeExcption("微信鉴权失败,没有得到用户信息！");
        }
        String openId = userWechatInfo.getOpenid();
        if (StringUtils.isBlank(openId)) {

            throw new MyRunTimeExcption("微信鉴权失败");
        }
        request.getSession().setAttribute(Constant.SESSION_OPEN_ID, openId);
        request.getSession().setAttribute(Constant.SESSION_WECHAT_USER_INFO, userWechatInfo);

    }



}
